#include "widget.h"
#include "ui_widget.h"

Widget::Widget(Qt::Orientations orientation,QWidget *parent)
    : QWidget(parent),m_orientation(orientation)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    m_orientation==Qt::Horizontal ? this->setMinimumHeight(100) : this->setMinimumWidth(100);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    auto rect=event->rect();
    //设置抗锯齿
    painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing,true);
    painter.fillRect(rect,QBrush(background));
    //绘制刻度
    painter.save();
    auto length=(m_orientation==Qt::Horizontal? rect.width(): rect.height());
    painter.setPen(QPen(textColor,1));
    painter.setFont(font);
    //水平像素刻度尺
    if(m_orientation==Qt::Horizontal)
    {
        auto height=rect.height();
        auto short_Line=height*0.75;
        auto long_Line=height*0.5;
        auto middle_Line=height*0.625;
        int temp=0;
        for(int i=0;i<length;i+=10)
        {
            if(temp%10==0)
            {
                painter.drawLine(QPointF(i,middle_Line),QPointF(i,height));
            }
            else if(temp%5==0)
            {
                painter.drawLine(QPointF(i,long_Line),QPointF(i,height));
                painter.drawText(QRect(i-50,0,100,50),Qt::AlignCenter | Qt::TextWordWrap,
                                 QString::number(i));
            }
            else
            {
                painter.drawLine(QPointF(i,short_Line),QPointF(i,height));
            }
            ++temp;
        }
    }
    //垂直像素刻度尺
    else
    {
        auto width=rect.width();
        auto short_Line=width*0.25;
        auto long_Line=width*0.5;
        auto middle_Line=width*0.375;
        int temp=0;
        for(int i=0;i<length;i+=10)
        {
            if(temp%10==0)
            {
                painter.drawLine(QPointF(middle_Line,i),QPointF(0,i));
            }
            else if(temp%5==0)
            {
                painter.drawLine(QPointF(long_Line,i),QPointF(0,i));
                painter.drawText(QRect(width/2,i-50,width/2,100),Qt::AlignCenter | Qt::TextWordWrap,
                                 QString::number(i));
            }
            else
            {
                painter.drawLine(QPointF(short_Line,i),QPointF(0,i));
            }
            ++temp;
        }
    }
    painter.restore();
    QWidget::paintEvent(event);
}

